package com.pig.consume.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.*;

/**
 * @author lizhiwei
 */
public class TextClient {
    private static ExecutorService executorNettyThread = Executors.newFixedThreadPool(20);
    private final String host;
    private final int port;

    private Channel channel;

    public TextClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        executorNettyThread.submit(() -> {
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                Bootstrap bootstrap = new Bootstrap()
                        .group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new TextClientInitializer());
                ChannelFuture connect = bootstrap.connect(host, port);
                channel = connect.sync().channel();
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                while (true) {
                    channel.writeAndFlush(in.readLine() + "\r\n");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        });

    }

    public void sendMsg(String msg) {
        channel.writeAndFlush(msg + "\r\n");
    }
}
